package com.kaifamiao.wendao.listener;

import com.kaifamiao.wendao.utils.DataSourceFactory;
import com.kaifamiao.wendao.utils.SnowflakeIdGenerator;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext application = event.getServletContext();

        // 初始化数据源
        DataSourceFactory factory = DataSourceFactory.getInstance();
        factory.init();

        // 将 当前"web application"路径 设置到 ServletContext对象中
        application.setAttribute("ctxPath", application.getContextPath());

        String dcid = application.getInitParameter("datacenterId");
        if(StringUtils.isEmpty(dcid) || StringUtils.isBlank(dcid)) {
            throw new RuntimeException("必须在web.xml中显式指定初始化参数: datacenterId");
        }
        Long datacenterId = Long.valueOf(dcid);
        String wid = application.getInitParameter("workerId");
        if(StringUtils.isEmpty(wid) || StringUtils.isBlank(wid)) {
            throw new RuntimeException("必须在web.xml中显式指定初始化参数: workerId");
        }
        Long workerId = Long.valueOf(wid);
        // 创建基于雪花算法的标识符生成器(用类变量予以缓存)
        SnowflakeIdGenerator.build( workerId, datacenterId );
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {

        // 释放数据源
        DataSourceFactory factory = DataSourceFactory.getInstance();
        factory.close();
    }

}
